#include "chat.h"
#include "ui_chat.h"
#include "main.h"
#include "historywindow.h"


//#include "mainwindow.h"
//#include "lockerwidget.h"
//#include "small_friend.h"
//#include "get_user.h"

//ChatWidget::ChatWidget(QString nuser_id)
//    :  user_id(nuser_id),ui(new Ui::Widget)
//{
//    qDebug() << "user_id" << user_id;
//    ui->setupUi(this);
//    senderhead = userMap[use_uid]->picture;
//    this->setWindowTitle("IM_software");
//    this->setWindowIcon(QIcon(":/new/prefix1/images/icons_head.png"));
////    ui->senderProgressBar->setValue(0);
////    ui->receiverProgressBar->setValue(0);
////    ui->senderFileName->setText("当前无正在传输的文件");
////    ui->receiverFileName->setText("当前无正在接收的文件");
//    m_socket = new SerSocket();

//    connect(ui->history_button,SIGNAL(clicked()),this,SLOT(on_history_button_clicked()));

//    connect(this,&ChatWidget::Text,m_socket,&SerSocket::ClientSendingText);
//    connect(m_socket,&SerSocket::GetMsgId,this,&ChatWidget::update_msgid);
//    connect(this,&ChatWidget::FilePath,m_socket,&SerSocket::ClientSendingFile);
//    connect(m_socket, &SerSocket::jindu, this, &ChatWidget::sendFile);

//    // 聊天框滚动效果
//    scrollarea = new QScrollArea(ui->liaotiankuang);
//    scrollarea->setWidgetResizable(true);
//    scrollarea->setMinimumSize(441, 266);
//    scrollarea->setStyleSheet("background-color: transparent;");
//    scrollareacontent = new QWidget(ui->liaotiankuang);
//    scrollarea->setWidget(scrollareacontent);
//    // 设置聊天框垂直
//    QVBoxLayout* scrollLayout = new QVBoxLayout();
//    scrollLayout->addWidget(scrollarea);
//    ui->liaotiankuang->setLayout(scrollLayout);

//    QGridLayout* glayout = new QGridLayout();
//    glayout->addWidget(scrollareacontent);
//    //    scrollareacontent->setLayout(glayout);
//    //    // 聊天框自适应大小
//    QSizePolicy sizePlc(QSizePolicy::Expanding, QSizePolicy::Expanding);
//    scrollareacontent->setSizePolicy(sizePlc);

//    // 聊天框内垂直布局
//    playout = new QVBoxLayout(scrollareacontent);
//    scrollareacontent->setLayout(playout);
//    ui->liaotiankuang->setStyleSheet("background-color: white;");

//}



ChatWidget::ChatWidget(Friend sender, Friend receiver, QPixmap senderHead, QPixmap receiverHead, QWidget *parent)
    : user_id("friend"), QWidget(parent), sender(sender), receiver(receiver), senderhead(senderHead), receivehead(receiverHead),
      ui(new Ui::Widget)
{
    ui->setupUi(this);
    //
    qDebug()<<sender.name;
    qDebug()<<sender.id;

    qDebug()<<receiver.name;
    qDebug()<<receiver.id;
    this->setWindowTitle(receiver.name);
    this->setWindowIcon(QIcon(":/new/prefix1/images/icons_head.png"));
    m_socket = new SerSocket();

    connect(this,&ChatWidget::Text,m_socket,&SerSocket::ClientSendingText);
    connect(m_socket,&SerSocket::GetMsgId,this,&ChatWidget::update_msgid);
    connect(this,&ChatWidget::FilePath,m_socket,&SerSocket::ClientSendingFile);
    connect(m_socket, &SerSocket::jindu, this, &ChatWidget::sendFile);
    connect(this,&ChatWidget::RFile,m_socket,&SerSocket::ClientSendingFRequese);
    connect(m_socket, &SerSocket::r_jindu, this, &ChatWidget::receiveFile);

    connect(m_socket,&SerSocket::showPicture,this,&ChatWidget::receivePicture);


    QGridLayout* glayout = new QGridLayout();
    // 设置双方信息
    ui->senderInfo->setFixedHeight(60);
    ui->receiverInfo->setFixedHeight(60);
    if(sender.ip == "-1")
        ui->senderInfo->setText("昵称："+sender.name+"\n职责："+sender.job+"\n离线");
    else
        ui->senderInfo->setText("昵称："+sender.name+"\n职责："+sender.job+"\nip："+sender.ip);

    if(receiver.ip == "-1")
        ui->receiverInfo->setText("昵称："+receiver.name+"\n职责："+receiver.job+"\n离线");
    else
        ui->receiverInfo->setText("昵称："+receiver.name+"\n职责："+receiver.job+"\nip："+receiver.ip);

//    ui->receiverInfo->setText("昵称："+receiver.name+"\n职责："+receiver.job+"\nip："+receiver.ip);
    ui->senderHead->setPixmap(senderHead);
    ui->receiverHead->setPixmap(receiverHead);

    // 聊天框滚动效果
    scrollarea = new QScrollArea(ui->liaotiankuang);
    scrollarea->setWidgetResizable(true);
    scrollarea->setMinimumSize(421, 266);
    scrollarea->setStyleSheet("background-color: transparent;");
    scrollareacontent = new QWidget(ui->liaotiankuang);
    scrollarea->setWidget(scrollareacontent);
    // 设置聊天框垂直
    QVBoxLayout* scrollLayout = new QVBoxLayout();
    scrollLayout->addWidget(scrollarea);
    ui->liaotiankuang->setLayout(scrollLayout);

    glayout->addWidget(scrollareacontent);
    //    scrollareacontent->setLayout(glayout);
    //    // 聊天框自适应大小
    QSizePolicy sizePlc(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scrollareacontent->setSizePolicy(sizePlc);

    // 聊天框内垂直布局
    playout = new QVBoxLayout(scrollareacontent);
    scrollareacontent->setLayout(playout);
    ui->liaotiankuang->setStyleSheet("background-color: white;");


    // 发给我的时候就有的，不知道干什么的
    //    mainwindow *window = new mainwindow();
    //    window->show();
    //    LockerWidget* a = new LockerWidget();
    //    a->show();
    //    user_information user1("001");
    //    small_friend* c = new small_friend(user1);
    //    c->show();
}

ChatWidget::~ChatWidget()
{
    delete ui;
}

void ChatWidget::resizeEvent(QResizeEvent *event){
    QSize newSize = ui->liaotiankuang->size();
    scrollarea->resize(newSize.width(), newSize.height());
}

void ChatWidget::on_send_clicked()
{
    // 先把文本框的消息取出来
    QString msg = ui->textEdit->toPlainText();
    qDebug() << msg;
    if(msg.isEmpty())
        return ;
    // 再清空文本框
    ui->textEdit->clear();

    qDebug() << ui->liaotiankuang->width() << " " << ui->liaotiankuang->height();
    qDebug() << scrollareacontent->width() << " " << scrollareacontent->height();

    QJsonObject text_bag;
    Message m_msg;
    if(receiver.id<800000){
        qDebug() << "friend";
        m_msg.msg = msg;
        m_msg.rid = receiver.id;
        m_msg.tid = sender.id;
        m_msg.time = QDateTime::currentDateTime();

        text_bag.insert("UID", QString::number(sender.id));
        text_bag.insert("RID",QString::number(receiver.id));
        text_bag.insert("content",msg);

    }
    else{
        qDebug() << "group";
        m_msg.msg = msg;
        m_msg.rid = receiver.id;
        m_msg.tid = use_uid.toInt();
        m_msg.time = QDateTime::currentDateTime();
        m_msg.show();

        text_bag.insert("UID", QString::number(sender.id));
        text_bag.insert("RID",QString::number(receiver.id));
        text_bag.insert("content",msg);
    }

    msg_que.enqueue(m_msg);

    //now_msg =ui->textEdit->toPlainText();
    //ui->history->appendPlainText(use_name+" [out] "+now_msg+"\n");
//    sendMessage(m_msg);

    ChatBubbleAndHead* b1=new ChatBubbleAndHead(SENDER,senderhead,receivehead, this);


    QJsonDocument jsonDocument;
    jsonDocument.setObject(text_bag);
    QByteArray tbox = jsonDocument.toJson();
    b1->set_txt(msg);
    //ChatBubbleAndHead* b2=new ChatBubbleAndHead(pkgmsg, 0);
    playout->addWidget(b1,0,Qt::AlignRight | Qt::AlignBottom);
    scrollarea->verticalScrollBar()->setValue(scrollarea->verticalScrollBar()->maximumHeight());

    emit Text(tbox,0x06);

    // playout->addWidget(b2,0,Qt::AlignLeft | Qt::AlignTop);


    //    ui->textBrowser->append(msg);
    //    ui->textBrowser->setStyleSheet("border: 1px solid gray; background-color: #f5f1f0;");
    //    ui->textBrowser->append(bubble1);
    // 再发送消息
}

void ChatWidget::on_file_button_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this, "请选择文件");
    if (!filePath.isEmpty()){
        // 上传服务器

        QJsonObject file_bag;
        file_bag.insert("UID", QString::number(sender.id));
        file_bag.insert("RID",QString::number(receiver.id));
        //        QString filePath = QFileDialog::getOpenFileName(this,"open","../");
        QFileInfo info(filePath);
        QString fileName = info.fileName();
        int fileSize = info.size();
        QString head = tr("%1##%2##%3").arg(fileName).arg(fileSize).arg("0");
        file_bag.insert("content",head);
        QJsonDocument jsonDocument;
        jsonDocument.setObject(file_bag);

        file_box fbox;
        fbox.info = jsonDocument.toJson();
        fbox.fpath = filePath;
        fbox.sz = fileSize;
        fbox.fname = fileName;
        fbox.uid = QString::number(sender.id).toUtf8().data();
        file_que.enqueue(fbox);
        //        now_msg = filePath;
        //        ui->history->appendPlainText(use_name+" [out] "+now_msg+"\n");
        Message m_msg;
        m_msg.msg = head;
        m_msg.rid = receiver.id;
        m_msg.tid = sender.id;
        m_msg.time = QDateTime::currentDateTime();
        msg_que.enqueue(m_msg);
        emit FilePath(fbox);

        // 发送文件的显示
        // sendFile(QFileInfo(filePath).fileName());

    }
}

void ChatWidget::sendMessage(QString msg){
    ChatBubbleAndHead* b1=new ChatBubbleAndHead(1,senderhead,receivehead, this);
    b1->set_txt(msg);
    playout->addWidget(b1,0,Qt::AlignRight | Qt::AlignBottom);
}
void ChatWidget::receiveMessage(QString msg){
    ChatBubbleAndHead* b1=new ChatBubbleAndHead(0,senderhead,receivehead, this);
    b1->set_txt(msg);
    playout->addWidget(b1,0,Qt::AlignLeft | Qt::AlignTop);
}

void ChatWidget::sendMessage(Message msg){
    msg.show();
    ChatBubbleAndHead* b1=new ChatBubbleAndHead(1,userMap[QString::number(msg.tid)]->picture,groupMap[QString::number(msg.rid)]->picture, this);
    b1->set_txt(msg.msg);
    playout->addWidget(b1,0,Qt::AlignRight | Qt::AlignBottom);
}
void ChatWidget::receiveMessage(Message msg){
    msg.show();
    ChatBubbleAndHead* b1=new ChatBubbleAndHead(0,groupMap[QString::number(msg.rid)]->picture,userMap[QString::number(msg.tid)]->picture, this);
    b1->set_txt(msg.msg);
    playout->addWidget(b1,0,Qt::AlignLeft | Qt::AlignTop);
}

void ChatWidget::sendFile(int val, QString fileName){
    // 传输文件进度
    ui->senderProgressBar->setValue(val);
    // 显示文件名;
    if(val==100)
        ui->senderFileName->setText("已完成发送："+fileName);
    else
        ui->senderFileName->setText("正在发送："+fileName);
}

void ChatWidget::receiveFile(int val, QString fileName){
    // 传输文件进度
    ui->receiverProgressBar->setValue(val);
    // 显示文件名
    if(val==100)
        ui->receiverFileName->setText("已完成接收："+fileName);
    else
        ui->receiverFileName->setText("正在接收："+fileName);
}

void ChatWidget::beforeReceiveFile(const QString& file_name,const QByteArray& info,const int& sz){
    ChatBubbleAndHead* b1=new ChatBubbleAndHead(0,senderhead,receivehead, this);
    b1->set_file(file_name,info,sz);
    playout->addWidget(b1,0,Qt::AlignLeft | Qt::AlignTop);
    // 自己确认后进行（待补充）
}

void ChatWidget::beforeReceivePicture(const QString& file_name,const QByteArray& info,const int& sz){
    QString dir = "D:/download";
    emit RFile(dir,file_name,info,sz,"picture");
}

void ChatWidget::sendPicture(const QString& path){
    QPixmap picture(path);
    ChatBubbleAndHead* b1=new ChatBubbleAndHead(SENDER,senderhead,receivehead, this);
    b1->set_picture(picture);
    qDebug()<<"send"<<picture.width()<<picture.height();
    playout->addWidget(b1,0,Qt::AlignRight | Qt::AlignTop);
    scrollarea->verticalScrollBar()->setValue(scrollarea->verticalScrollBar()->maximumHeight());
}

void ChatWidget::receivePicture(const QString& path){
    QPixmap picture(path);
    ChatBubbleAndHead* b1=new ChatBubbleAndHead(RECEIVER,senderhead,receivehead, this);
    b1->set_picture(picture);
    qDebug()<<"rece"<<picture.width()<<picture.height();
    playout->addWidget(b1,0,Qt::AlignLeft | Qt::AlignTop);
    scrollarea->verticalScrollBar()->setValue(scrollarea->verticalScrollBar()->maximumHeight());
}



//void ChatWidget::receiveFile(QString fileName){
//    // 显示正在传输的文件
//    int jindu = 0;
//    ui->senderFileName->setText("正在接收："+fileName);
//    ui->senderProgressBar->setValue(jindu);
//    // 传输文件

//    // 进度条
//    ui->senderProgressBar->setValue(jindu);
//    // 完成后
//    ui->senderFileName->setText("已完成接收："+fileName);
//}


void ChatWidget::update_msgid(const int& mid){
    Message m_msg = msg_que.dequeue();
    m_msg.id = mid;
    m_msg.show();
    db.AddMessage(m_msg);
}

void ChatWidget::receiveFile_CB2C(const QString& filename,const QByteArray& info,const int& sz){
    //接收文件！
    QString dir = "D:/download";   //加上自己的默认地址
    emit RFile(dir,filename,info,sz,"file");
    qDebug() << "准备接受！"+filename;
}

//接收图片逻辑
void ChatWidget::on_picture_button_clicked()
{
    QString filter = "Images (*.png *.xpm *.jpg *.bmp *.gif)";//文件过滤器
    QString filePath = QFileDialog::getOpenFileName(this, "请选择文件","", filter);
    if (!filePath.isEmpty()) {
        // 打开成功，filePath 就是所选文件的路径
        // 这里执行图片传输的逻辑
        QJsonObject file_bag;
        file_bag.insert("UID", QString::number(sender.id));
        file_bag.insert("RID",QString::number(receiver.id));
        //        QString filePath = QFileDialog::getOpenFileName(this,"open","../");
        QFileInfo info(filePath);
        QString fileName = info.fileName();
        int fileSize = info.size();
        QString head = tr("%1##%2##%3").arg(fileName).arg(fileSize).arg("1");
        file_bag.insert("content",head);
        QJsonDocument jsonDocument;
        jsonDocument.setObject(file_bag);

        file_box fbox;
        fbox.info = jsonDocument.toJson();
        fbox.fpath = filePath;
        fbox.sz = fileSize;
        fbox.fname = fileName;
        fbox.uid = QString::number(sender.id).toUtf8().data();
        file_que.enqueue(fbox);
        //        now_msg = filePath;
        //        ui->history->appendPlainText(use_name+" [out] "+now_msg+"\n");

        //-------------------------------------------------不知道是否需要传此内容进消息，按理说下载文件需要mid
        Message m_msg;
        m_msg.msg = head;
        m_msg.rid = receiver.id;
        m_msg.tid = sender.id;
        m_msg.time = QDateTime::currentDateTime();
        msg_que.enqueue(m_msg);
        //--------------------------------------------------------------------------------
        sendPicture(filePath);
        emit FilePath(fbox);

    }
    //    else {
    //        // 用户取消了选择
    //        QMessageBox::information(this, "Info", "没有选择图片");
    //    }
}

void ChatWidget::on_history_button_clicked()
{
    qDebug()<<"lishi";
    qDebug()<<"user_id"<<user_id;
    historywindow* new_window = new historywindow(QString::number(receiver.id));
}
void ChatWidget::updateIP(QString ip){
    if(ip == "-1")
        ui->receiverInfo->setText("昵称："+receiver.name+"\n职责："+receiver.job+"\n离线");
    else
        ui->receiverInfo->setText("昵称："+receiver.name+"\n职责："+receiver.job+"\nip："+ip);
}
